﻿// 本动态库从调用方接受JSON字符串，解析为积分模块所需的结构化数据，调用积分库
#include "pch.h"

// TFileItem构造函数
TFileItem::TFileItem() : isFolder(false), fileSize(0), createTime(0), modifyTime(0)
{
    std::fill_n(fileName, sizeof(fileName), '\0');
    std::fill_n(extName, sizeof(extName), '\0');
}

// TSample构造函数
TSample::TSample() : SmpType(BY_SMP), GatherTime(0), Minutes(0), CreateTime(0), UpdateTime(0)
{
    std::fill_n(ID, sizeof(ID), '\0');
    std::fill_n(Name, sizeof(Name), '\0');
    std::fill_n(MethodName, sizeof(MethodName), '\0');
    std::fill_n(InstName, sizeof(InstName), '\0');
    std::fill_n(BatchCode, sizeof(BatchCode), '\0');
    std::fill_n(BslName, sizeof(BslName), '\0');
    std::fill_n(GatherLocation, sizeof(GatherLocation), '\0');
    std::fill_n(ConcUnit, sizeof(ConcUnit), '\0');
    std::fill_n(Note, sizeof(Note), '\0');
}

// TInject构造函数
TInject::TInject() : Sn(0), StartTime(0), StopTime(0), AnalMinutes(0), VialNos(0), Syringe(0)
{
    std::fill_n(SmpID, sizeof(SmpID), '\0');
    std::fill_n(InjID, sizeof(InjID), '\0');
    std::fill_n(GUID, sizeof(GUID), '\0');
    std::string uuid_v4 = uuid::generate_v4();
    STRING_COPY(uuid_v4.c_str(), GUID);
}

// TInstHead构造函数
TInstHead::TInstHead() : ID(0), Type(0), SignalNo(0), FromAIACDF(0)
{
    std::fill_n(Name, sizeof(Name), '\0');
    std::fill_n(TypeAbbr, sizeof(TypeAbbr), '\0');
    std::fill_n(TypeName, sizeof(TypeName), '\0');
    std::fill_n(Model, sizeof(Model), '\0');
    std::fill_n(MarkNo, sizeof(MarkNo), '\0');
    std::fill_n(Manufacturer, sizeof(Manufacturer), '\0');
    std::fill_n(AIACDFName, sizeof(AIACDFName), '\0');
    std::fill_n(Description, sizeof(Description), '\0');
    std::fill_n(ExperimentTitle, sizeof(ExperimentTitle), '\0');
    std::fill_n(DatasetOwner, sizeof(DatasetOwner), '\0');
    std::fill_n(OperatorName, sizeof(OperatorName), '\0');
}

// TOvenCond构造函数
TOvenCond::TOvenCond() : Available(0), MaxTempRamps(0), MaxTemp(0.0), Equilibry(0.0), Temperature(0.0), TempMode(0)
{
    std::fill_n(Model, sizeof(Model), '\0');
}

// TInletCond构造函数
TInletCond::TInletCond() : Available(0), Type(0), InjMode(0), ASType(0), TempMode(0), SplitMode(0), PurgeOn(0), Temperature(0.0), CarrierFlow(0.0), Pressure(0.0), SplitFlow(0.0), PurgeFlow(0.0), PurgeTime(0.0), SplitlessHold(0.0)
{
    std::fill_n(TypeAbbr, sizeof(TypeAbbr), '\0');
    std::fill_n(TypeName, sizeof(TypeName), '\0');
    std::fill_n(InjectModel, sizeof(InjectModel), '\0');
    std::fill_n(CarrierGas, sizeof(CarrierGas), '\0');
    std::fill_n(SplitRatio, sizeof(SplitRatio), '\0');
}

// TColumnCond构造函数
TColumnCond::TColumnCond() : Available(0), Type(0), FreqIdx(0), mmLength(0), Diameter(0.0), FilmThick(0.0), DeadTime(0.0), Flow(0.0), Pressure(0.0), PFMode(0)
{
    std::fill_n(TypeAbbr, sizeof(TypeAbbr), '\0');
    std::fill_n(TypeName, sizeof(TypeName), '\0');
    std::fill_n(Model, sizeof(Model), '\0');
}

// TDetectCond构造函数
TDetectCond::TDetectCond() : Available(0), Type(0), RangeMax(0.0), RangeMin(0.0), RangeValue(0.0), Sensitivity(0.0), Temperature(0.0), H2Flow(0.0), AirFlow(0.0), RefFlow(0.0), AnodeFlow(0.0), Current(0.0), MakeupFlow(0.0), MakeupMode(0), GC_RangeIDInc(0), WaveLength(0.0), WaveLengthMode(0), SuppCurrent(0.0), SuppAvailable(0)
{
    std::fill_n(TypeAbbr, sizeof(TypeAbbr), '\0');
    std::fill_n(TypeName, sizeof(TypeName), '\0');
    std::fill_n(Model, sizeof(Model), '\0');
    std::fill_n(DeteUnit, sizeof(DeteUnit), '\0');
    std::fill_n(RangeOptions, sizeof(RangeOptions), '\0');
    std::fill_n(MakeupGas, sizeof(MakeupGas), '\0');
}

// TAuxCond构造函数
TAuxCond::TAuxCond() : Available(0), Type(0), SensType(0), OnOff(0), PosNo(0), Temperature(0.0), TempMode(0), Pressure(0.0), PresMode(0), Flow(0.0), FlowMode(0)
{
    std::fill_n(TypeAbbr, sizeof(TypeAbbr), '\0');
    std::fill_n(TypeName, sizeof(TypeName), '\0');
    std::fill_n(Model, sizeof(Model), '\0');
}

// TPumpCond构造函数
TPumpCond::TPumpCond() : Available(0), Type(0), GradPresMode(0), MaxPressure(0.0), MinPressure(0.0), TotalFlow(0.0), Pressure(0.0)
{
    for (int32_t i = 0; i < 4; ++i)
    {
        SolRatio[i] = 0.0;
        SolUsed[i] = 0;
        std::fill_n(SolName[i], sizeof(SolName[i]), '\0');
    }
    std::fill_n(FlowUnit, sizeof(FlowUnit), '\0');
    std::fill_n(PresUnit, sizeof(PresUnit), '\0');
    std::fill_n(Model, sizeof(Model), '\0');
}

// TAuxCondEx构造函数
TAuxCondEx::TAuxCondEx() : Available(0), Type(0), SensType(0), OnOff(0), PosNo(0)
{
    std::fill_n(TypeAbbr, sizeof(TypeAbbr), '\0');
    std::fill_n(TypeName, sizeof(TypeName), '\0');
    std::fill_n(Model, sizeof(Model), '\0');
    int32_t count = sizeof(RampItems) / sizeof(TFloatRampItem);
    for (int32_t i = 0; i < count; ++i)
    {
        RampItems[i] = TFloatRampItem();
    }
}

// TInstCond构造函数
TInstCond::TInstCond() : OvenTempItemsCount(0), InletTempItemsCount(0), ColumnPFItemsCount(0), MakeupFlowItemsCount(0), PumpGradItemsCount(0), WaveCountItemsCount(0), AuxCondExsCount(0)
{
    std::fill_n(Name, sizeof(Name), '\0');
    for (int32_t i = 0; i < C64; ++i)
    {
        OvenTempItems[i] = TRampItem();
        InletTempItems[i] = TRampItem();
        ColumnPFItems[i] = TRampItem();
        MakeupFlowItems[i] = TRampItem();
    }
    for (int32_t i = 0; i < C64; ++i)
    {
        PumpGradItems[i] = TPumpGradItem();
        WaveLengthItems[i] = TWaveLengthItem();
        AuxCondExs[i] = TAuxCondEx();
    }
}

// TAnalResult构造函数
TAnalResult::TAnalResult() : Area(0.0), AreaPer(0.0), Conc(0.0), Areas(0.0), Arear(0.0), Areae(0.0),
                             ALeft(0.0), ARight(0.0), Idno(0), RTime(0.0f), Height(0.0f),
                             W50(0.0f), Sigma5(0.0f), Plates(0.0f), Resolution(0.0f), Symmetry(0.0f),
                             M1(0.0f), M2(0.0f), fts(0.0f), fte(0.0f), ts(0), tr(0.0f), te(0),
                             hs(0.0f), hsv(0.0f), hr(0.0f), he(0.0f), hev(0.0f)
{
    std::fill_n(Name, sizeof(Name), '\0');
    std::fill_n(TypeCode, sizeof(TypeCode), '\0');
}

// TSynResult构造函数
TSynResult::TSynResult() : Type(0), OkState(0), Tr(0.0f), Band(0.0f), cLower(0.0f),
                           cUpper(0.0f), Area(0.0), Height(0.0), Conc(0.0), ConcEx(0.0),
                           dLimit(0.0f), ConcUnitFactor(0)
{
    std::fill_n(Name, sizeof(Name), '\0');
}

// TGroupList构造函数
TGroupList::TGroupList() : Continuous(0), NeedRefId(0), tLower(0.0f), tUpper(0.0f),
                           cLower(0.0f), cUpper(0.0f), dLimit(0.0f), ConcUnitFactor(0)
{
    std::fill_n(Name, sizeof(Name), '\0');
    std::fill_n(RefIdName, sizeof(RefIdName), '\0');
    for (int32_t i = 0; i < C64; ++i)
    {
        std::fill_n(IdNames[i], sizeof(IdNames[i]), '\0');
    }
}

// TSegmentList构造函数
TSegmentList::TSegmentList() : SegmentMode(0), SegmentCount(0)
{
    for (int32_t i = 0; i < C16; ++i)
    {
        SegmentItem[i] = TSegmentItem();
    }
}

// TCompList构造函数
TCompList::TCompList() : f0(0.0f), f1(0.0f), f2(0.0f), f3(0.0f), k(0.0f), k1(0),
                         cLower(0.0f), cUpper(0.0f), r(0.0f), basedOn(ON_AREA), weight(0.0),
                         Time(0.0f), band(0.0f), istdNoSelf(0), TypeEx(0), istdNoUsed(0)
{
    std::fill_n(Name, sizeof(Name), '\0');
}

// TCalibList构造函数
TCalibList::TCalibList()
{
    std::fill_n(OrgName, sizeof(OrgName), '\0');
    std::fill_n(GUID, sizeof(GUID), '\0');
    for (int32_t i = 0; i < C256; ++i)
    {
        StdConc[i] = 0.0;
        Resp[i] = 0.0;
        shift[i] = 0.0;
    }
    std::string uuid_v4 = uuid::generate_v4();
    STRING_COPY(uuid_v4.c_str(), GUID);
}

// TCalibResult构造函数
TCalibResult::TCalibResult() : Idno(0), f0(0.0), f1(0.0), f2(0.0), f3(0.0), r(0.0)
{
    std::fill_n(Name, sizeof(Name), '\0');
}

TMethodHead_::TMethodHead_() : Identifier(0), Version(0), CreateTime(0), UpdateTime(0), EPara(), IPara(), QualitBy(BY_BAND), metric(),
                               autoIPara(), UkPkFactor{TUkPkFactor(), TUkPkFactor(), TUkPkFactor(), TUkPkFactor()},
                               XUnit{1.0 / 1200, 1.0 / 1200, 1.0 / 1200, 1.0 / 1200}, YUnit{100.0, 100.0, 100.0, 100.0}, CalibHead(),
                               EventListOffset(0), EventListCount(0), CompListOffset(0), CompListCount(0), GroupListOffset(0), GroupListCount(0),
                               SegmentListOffset(0), SegmentListCount(0), CalibListOffset(0), CalibListCount(0), CalibResultOffset(0), CalibResultCount(0)
{
    std::fill_n(Name, sizeof(Name), '\0');
    std::fill_n(GUID, sizeof(GUID), '\0');
    std::fill_n(ProjectID, sizeof(ProjectID), '\0');
    std::fill_n(ProjectName, sizeof(ProjectName), '\0');
    std::fill_n(RelatedID, sizeof(RelatedID), '\0');
    std::fill_n(Note, sizeof(Note), '\0');
    std::string uuid_v4 = uuid::generate_v4();
    STRING_COPY(uuid_v4.c_str(), GUID);
}

// TMethodHead构造函数
TMethodHead::TMethodHead() : TMethodHead_()
{
    std::fill_n(Reserved1, sizeof(Reserved1), '\0');
}

// TMethodFile构造函数
TMethodFile::TMethodFile() : TMethodHead(), HeadCRC(0), DataCRC(0),
                             EventList(nullptr), CompList(nullptr), GroupList(nullptr),
                             SegmentList(nullptr), CalibList(nullptr), CalibResult(nullptr)
{
    std::fill_n(Reserved2, sizeof(Reserved2), '\0');
}

// 计算头部长度
int32_t TMethodFile::getHeadLength() const
{
    return static_cast<int32_t>(sizeof(TMethodHead));
}

// 计算数据长度
int32_t TMethodFile::getDataLength() const
{
    return EventListCount * sizeof(TEventList) +
           CompListCount * sizeof(TCompList) +
           GroupListCount * sizeof(TGroupList) +
           SegmentListCount * sizeof(TSegmentList) +
           CalibListCount * sizeof(TCalibList) +
           CalibResultCount * sizeof(TCalibResult);
}

// 计算总长度
int32_t TMethodFile::getTotalLength() const
{
    return getHeadLength() + 2 * static_cast<int32_t>(sizeof(uint64_t)) + getDataLength();
}

// 从缓冲区复制头部信息
bool TMethodFile::copyHeadFromBuffer(const BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TMethodFile::copyHeadFromBuffer 参数data为空指针。");
        return false;
    }
    if (dataLength < getHeadLength())
    {
        PUSH_ERROR("函数 TMethodFile::copyHeadFromBuffer 数据空间不足(datalength=%d, getHeadLength=%d)。", dataLength, getHeadLength());
        return false;
    }
    BYTE_COPY(data, this, getHeadLength());
    return true;
}

// 将头部信息复制到缓冲区
bool TMethodFile::copyHeadToBuffer(BYTE *data, int32_t dataLength) const
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TMethodFile::copyHeadToBuffer 参数data为空指针。");
        return false;
    }
    if (dataLength < getHeadLength())
    {
        PUSH_ERROR("函数 TMethodFile::copyHeadToBuffer 数据空间不足(datalength=%d, getHeadLength=%d)。", dataLength, getHeadLength());
        return false;
    }
    BYTE_COPY(this, data, getHeadLength());
    return true;
}

// 从缓冲区复制指针指向的数据
bool TMethodFile::copyPtrFromBuffer(const BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 参数data为空指针。");
        return false;
    }

    if (!copyListFromBuffer(data, EventListCount, EventListOffset, EventList, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 调用 copyListFromBuffer 失败。");
        return false;
    }

    if (!copyListFromBuffer(data, CompListCount, CompListOffset, CompList, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 调用 copyListFromBuffer 失败。");
        return false;
    }

    if (!copyListFromBuffer(data, GroupListCount, GroupListOffset, GroupList, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 调用 copyListFromBuffer 失败。");
        return false;
    }

    if (!copyListFromBuffer(data, SegmentListCount, SegmentListOffset, SegmentList, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 调用 copyListFromBuffer 失败。");
        return false;
    }

    if (!copyListFromBuffer(data, CalibListCount, CalibListOffset, CalibList, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 调用 copyListFromBuffer 失败。");
        return false;
    }

    if (!copyListFromBuffer(data, CalibResultCount, CalibResultOffset, CalibResult, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 调用 copyListFromBuffer 失败。");
        return false;
    }

    return true;
}

// 将指针指向的数据复制到缓冲区
bool TMethodFile::copyPtrToBuffer(BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrToBuffer 参数data为空指针。");
        return false;
    }
    int32_t offset = getHeadLength() + 2 * static_cast<int32_t>(sizeof(uint64_t));

    if (!copyListToBuffer(data, EventListCount, EventListOffset, EventList, offset, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrToBuffer 调用 copyListToBuffer 失败。");
        return false;
    }
    if (!copyListToBuffer(data, CompListCount, CompListOffset, CompList, offset, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrToBuffer 调用 copyListToBuffer 失败。");
        return false;
    }
    if (!copyListToBuffer(data, GroupListCount, GroupListOffset, GroupList, offset, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrToBuffer 调用 copyListToBuffer 失败。");
        return false;
    }
    if (!copyListToBuffer(data, SegmentListCount, SegmentListOffset, SegmentList, offset, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrToBuffer 调用 copyListToBuffer 失败。");
        return false;
    }
    if (!copyListToBuffer(data, CalibListCount, CalibListOffset, CalibList, offset, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrToBuffer 调用 copyListToBuffer 失败。");
        return false;
    }
    if (!copyListToBuffer(data, CalibResultCount, CalibResultOffset, CalibResult, offset, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrToBuffer 调用 copyListToBuffer 失败。");
        return false;
    }
    return true;
}

// 将数据复制到缓冲区
bool TMethodFile::copyToBuffer(BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TMethodFile::copyToBuffer 参数data为空指针。");
        return false;
    }
    int32_t CRCLength = 2 * static_cast<int32_t>(sizeof(uint64_t));
    if (!copyPtrToBuffer(data, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyToBuffer 调用 copyPtrToBuffer 失败。");
        return false;
    }
    if (!copyHeadToBuffer(data, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyToBuffer 调用 copyHeadToBuffer 失败。");
        return false;
    }
    init_crc64_table();
    HeadCRC = calculate_crc64(reinterpret_cast<const char *>(data), getHeadLength());
    init_crc64_table();
    DataCRC = calculate_crc64(reinterpret_cast<const char *>(data + getHeadLength() + CRCLength), getDataLength());
    BYTE_COPY(&HeadCRC, data + getHeadLength(), sizeof(HeadCRC));
    BYTE_COPY(&DataCRC, data + getHeadLength() + sizeof(HeadCRC), sizeof(DataCRC));
    return true;
}

// 从缓冲区复制数据
bool TMethodFile::copyFromBuffer(BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TMethodFile::copyFromBuffer 参数data为空指针。");
        return false;
    }

    // 复制Head数据
    if (dataLength < getHeadLength())
    {
        PUSH_ERROR("函数 TMethodFile::copyFromBuffer 数据空间不足(dataLength=%d, getHeadLength()=%d。", dataLength, getHeadLength());
        return false;
    }
    int32_t CRCLength = 2 * static_cast<int32_t>(sizeof(uint64_t));
    uint64_t storedHeadCRC = *reinterpret_cast<uint64_t *>(data + getHeadLength());
    uint64_t storedDataCRC = *reinterpret_cast<uint64_t *>(data + getHeadLength() + sizeof(HeadCRC));
    init_crc64_table();
    uint64_t calculatedHeadCRC = calculate_crc64(reinterpret_cast<const char *>(data), getHeadLength());
    if (calculatedHeadCRC != storedHeadCRC)
    {
        PUSH_ERROR("函数 TMethodFile::copyFromBuffer HeadCRC校验失败。");
        return false;
    }
    if (!copyHeadFromBuffer(data, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyFromBuffer 调用 copyHeadFromBuffer 失败。");
        return false;
    }

    // 复制Data数据
    if (dataLength < getHeadLength())
    {
        PUSH_ERROR("函数 TMethodFile::copyFromBuffer 数据空间不足(dataLength=%d, getHeadLength()=%d, CRCLength=%d, getDataLength()=%d。",
                   dataLength, getHeadLength(), CRCLength, getDataLength());
        return false;
    }
    init_crc64_table();
    uint64_t calculatedDataCRC = calculate_crc64(reinterpret_cast<const char *>(data + getHeadLength() + CRCLength), getDataLength());
    if (calculatedDataCRC != storedDataCRC)
    {
        PUSH_ERROR("函数 TMethodFile::copyFromBuffer DataCRC校验失败。");
        return false;
    }

    if (!copyPtrFromBuffer(data, dataLength))
    {
        PUSH_ERROR("函数 TMethodFile::copyFromBuffer 调用 copyPtrFromBuffer 失败。");
        return false;
    }

    // 复制CRC校验数据
    HeadCRC = calculatedHeadCRC;
    DataCRC = calculatedDataCRC;

    return true;
}

// TOrgHead_构造函数
TOrgHead_::TOrgHead_() : Identifier(0xAABBCCDD), Version(0x00000001), Type(0), Detector(0x0001ffff), CreateTime(0), UpdateTime(0), BlankMode(SUB_NONE), Frequency(20.0),
                         Sample{TSample(), TSample(), TSample(), TSample()}, Inject{TInject(), TInject(), TInject(), TInject()},
                         InstCondOffset{0, 0, 0, 0}, InstCondLength{0, 0, 0, 0}, RawDataOffset{0, 0, 0, 0}, RawDataCount{0, 0, 0, 0},
                         MethodOffset(0), MethodLength(0), AnalResultOffset{0, 0, 0, 0}, AnalResultCount{0, 0, 0, 0},
                         SynResultOffset{0, 0, 0, 0}, SynResultCount{0, 0, 0, 0}, StudyDataOffset{0, 0, 0, 0}, StudyDataCount{0, 0, 0, 0},
                         BlankDataOffset{0, 0, 0, 0}, BlankDataCount{0, 0, 0, 0}, BlankResultOffset{0, 0, 0, 0}, BlankResultCount{0, 0, 0, 0}
{
    std::fill_n(Name, sizeof(Name), '\0');
    std::fill_n(GUID, sizeof(GUID), '\0');
    std::fill_n(ProjectID, sizeof(ProjectID), '\0');
    std::fill_n(ProjectName, sizeof(ProjectName), '\0');
    for (int32_t i = 0; i < C4; ++i)
    {
        std::fill_n(XUnit[i], sizeof(XUnit[i]), '\0');
        std::fill_n(YUnit[i], sizeof(YUnit[i]), '\0');
        std::fill_n(RelatedID[i], sizeof(RelatedID[i]), '\0');
        std::fill_n(Note[i], sizeof(Note[i]), '\0');
    }
    std::string uuid_v4 = uuid::generate_v4();
    STRING_COPY(uuid_v4.c_str(), GUID);
}

// TOrgHead构造函数
TOrgHead::TOrgHead() : TOrgHead_()
{
    std::fill_n(Reserved1, sizeof(Reserved1), '\0');
}

// TOrgFile构造函数
TOrgFile::TOrgFile() : TOrgHead(), HeadCRC(0), DataCRC(0), InstCond{nullptr, nullptr, nullptr, nullptr}, RawData{nullptr, nullptr, nullptr, nullptr}, Method(nullptr), AnalResult{nullptr, nullptr, nullptr, nullptr}, SynResult{nullptr, nullptr, nullptr, nullptr}, StudyData{nullptr, nullptr, nullptr, nullptr}, BlankData{nullptr, nullptr, nullptr, nullptr}, BlankResult{nullptr, nullptr, nullptr, nullptr}
{
    std::fill_n(Reserved2, sizeof(Reserved2), '\0');
}

// 计算头部长度
int32_t TOrgFile::getHeadLength() const
{
    return static_cast<int32_t>(sizeof(TOrgHead));
}

// 计算数据长度
int32_t TOrgFile::getDataLength() const
{
    int32_t length = 0;
    length += MethodLength;
    for (int32_t i = 0; i < C4; ++i)
    {
        if (isValidChannel(Detector, i))
        {
            length += InstCondLength[i];
            length += RawDataCount[i] * sizeof(TRawItem);
            length += AnalResultCount[i] * sizeof(TAnalResult);
            length += SynResultCount[i] * sizeof(TSynResult);
            length += StudyDataCount[i] * sizeof(int32_t);
            length += BlankDataCount[i] * sizeof(int32_t);
            length += BlankResultCount[i] * sizeof(TAnalResult);
        }
    }
    return length;
}

// 计算总长度
int32_t TOrgFile::getTotalLength() const
{
    return getHeadLength() + 2 * static_cast<int32_t>(sizeof(uint64_t)) + getDataLength();
}

// 从缓冲区复制头部信息
bool TOrgFile::copyHeadFromBuffer(const BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TOrgFile::copyHeadFromBuffer 参数data为空指针。");
        return false;
    }
    if (dataLength < getHeadLength())
    {
        PUSH_ERROR("函数 TMethodFile::copyHeadFromBuffer 数据空间不足(datalength=%d, getHeadLength=%d)。", dataLength, getHeadLength());
        return false;
    }
    BYTE_COPY(data, this, getHeadLength());
    return true;
}

// 将头部信息复制到缓冲区
bool TOrgFile::copyHeadToBuffer(BYTE *data, int32_t dataLength) const
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TOrgFile::copyHeadToBuffer 参数data为空指针。");
        return false;
    }
    if (dataLength < getHeadLength())
    {
        PUSH_ERROR("函数 TMethodFile::copyHeadToBuffer 数据空间不足(datalength=%d, getHeadLength=%d)。", dataLength, getHeadLength());
        return false;
    }
    BYTE_COPY(this, data, getHeadLength());
    return true;
}

// 从缓冲区复制指针指向的数据
bool TOrgFile::copyPtrFromBuffer(const BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TOrgFile::copyPtrFromBuffer 参数data为空指针。");
        return false;
    }

    // 仪器条件
    for (int32_t chn = 0; chn < C4; ++chn)
    {
        if (InstCondOffset[chn] > 0)
        {
            InstCond[chn] = std::make_shared<TInstCond>();
            if (InstCondLength[chn] != sizeof(TInstCond))
            {
                PUSH_ERROR("函数 TOrgFile::copyPtrFromBuffer chn=%d,InstCondLength与结构TInstCond长度不符。", chn);
                return false;
            }
            if (dataLength < InstCondOffset[chn] + InstCondLength[chn])
            {
                PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 数据空间不足(datalength=%d, InstCondOffset[%d]=%d,InstCondLength[%d]=%d)。",
                           chn, dataLength, chn, InstCondOffset[chn], chn, InstCondLength[chn]);
                return false;
            }
            BYTE_COPY(data + InstCondOffset[chn], InstCond[chn].get(), InstCondLength[chn]);
        }
        else
        {
            InstCond[chn] = nullptr;
        }
    }

    // 谱图数据
    COPY_FROM_BUFFER_C4(RawData);

    // 方法数据

    Method = std::make_shared<TMethodFile>();
    try
    {
        if (!Method.get()->copyFromBuffer(const_cast<BYTE *>(data + MethodOffset), dataLength - MethodOffset))
        {
            PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 调用Method->copyFromBuffer失败。");
            return false;
        }
    }
    catch (const std::exception &e)
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 调用Method->copyFromBuffer失败: %s", std::string(e.what()).c_str());
        return false;
    }
    if (MethodLength != Method.get()->getTotalLength())
    {
        PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 方法数据长度不匹配: MethodLength=%d, TMethodFile::getTotalLength()=%d。",
                   MethodLength, Method.get()->getTotalLength());
        return false;
    }

    // 分析结果、综合结果、学习数据、空白数据、空白结果
    COPY_FROM_BUFFER_C4(AnalResult);
    COPY_FROM_BUFFER_C4(SynResult);
    COPY_FROM_BUFFER_C4(StudyData);
    COPY_FROM_BUFFER_C4(BlankData);
    COPY_FROM_BUFFER_C4(BlankResult);

    return true;
}

// 将指针指向的数据复制到缓冲区
bool TOrgFile::copyPtrToBuffer(BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("TOrgFile::copyPtrToBuffer指针data为nullptr。");
        return false;
    }
    int32_t offset = getHeadLength() + 2 * static_cast<int32_t>(sizeof(uint64_t));

    // 仪器条件
    for (int32_t chn = 0; chn < C4; ++chn)
    {
        if (InstCond[chn])
        {
            InstCondOffset[chn] = offset;
            InstCondLength[chn] = sizeof(TInstCond);
            if (dataLength < InstCondOffset[chn] + InstCondLength[chn])
            {
                PUSH_ERROR("函数 TMethodFile::copyPtrFromBuffer 数据空间不足(datalength=%d, InstCondOffset[%d]=%d,InstCondLength[%d]=%d)。",
                           chn, dataLength, chn, InstCondOffset[chn], chn, InstCondLength[chn]);
                return false;
            }
            BYTE_COPY(InstCond[chn].get(), data + offset, sizeof(TInstCond));
            offset += InstCondLength[chn];
        }
        else
        {
            InstCondOffset[chn] = 0;
            InstCondLength[chn] = 0;
        }
    }

    // 谱图数据
    COPY_TO_BUFFER_C4(RawData);

    // 方法数据
    if (Method.get() != nullptr)
    {
        MethodOffset = offset;
        MethodLength = Method.get()->getTotalLength();
        try
        {
            if (!Method.get()->copyToBuffer(data + offset, dataLength - offset))
            {
                PUSH_ERROR("TOrgFile::copyPtrToBuffer调用Method->copyToBuffer失败。");
                return false;
            }
        }
        catch (const std::exception &e)
        {
            PUSH_ERROR("TOrgFile::copyPtrToBuffer调用Method->copyToBuffer失败:%s。", std::string(e.what()).c_str());
            return false;
        }
        offset += MethodLength;
    }

    COPY_TO_BUFFER_C4(AnalResult);
    COPY_TO_BUFFER_C4(SynResult);
    COPY_TO_BUFFER_C4(StudyData);
    COPY_TO_BUFFER_C4(BlankData);
    COPY_TO_BUFFER_C4(BlankResult);
    return true;
}

// 将数据复制到缓冲区
bool TOrgFile::copyToBuffer(BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数 TOrgFile::copyToBuffer 参数data为空指针。");
        return false;
    }
    int32_t CRCLength = 2 * static_cast<int32_t>(sizeof(uint64_t));
    int32_t headLen = getHeadLength();

    if (!copyPtrToBuffer(data, dataLength))
    {
        PUSH_ERROR("函数 TOrgFile::copyToBuffer 调用 copyPtrToBuffer 失败。");
        return false;
    }
    if (!copyHeadToBuffer(data, dataLength))
    {
        PUSH_ERROR("函数 TOrgFile::copyToBuffer 调用 copyHeadToBuffer 失败。");
        return false;
    }
    init_crc64_table();
    HeadCRC = calculate_crc64(reinterpret_cast<const char *>(data), headLen);
    init_crc64_table();
    DataCRC = calculate_crc64(reinterpret_cast<const char *>(data + headLen + CRCLength), getDataLength());
    BYTE_COPY(&HeadCRC, data + headLen, sizeof(HeadCRC));
    BYTE_COPY(&DataCRC, data + headLen + sizeof(HeadCRC), sizeof(DataCRC));
    return true;
}

// 从缓冲区复制数据
bool TOrgFile::copyFromBuffer(BYTE *data, int32_t dataLength)
{
    if (data == nullptr)
    {
        PUSH_ERROR("函数copyFromBuffer参数data为空指针。");
        return false;
    }

    // Head数据复制
    if (dataLength < getHeadLength())
    {
        PUSH_ERROR("函数 TOrgFile::copyFromBuffer 数据空间不足(datalength=%d, getHeadLength()=%d。", dataLength, getHeadLength());
        return false;
    }
    int32_t CRCLength = 2 * static_cast<int32_t>(sizeof(uint64_t));
    uint64_t storedHeadCRC = *reinterpret_cast<uint64_t *>(data + getHeadLength());
    uint64_t storedDataCRC = *reinterpret_cast<uint64_t *>(data + getHeadLength() + sizeof(HeadCRC));
    init_crc64_table();
    uint64_t calculatedHeadCRC = calculate_crc64(reinterpret_cast<const char *>(data), getHeadLength());
    if (calculatedHeadCRC != storedHeadCRC)
    {
        PUSH_ERROR("函数copyFromBuffer Head CRC校验失败。");
        return false;
    }
    if (!copyHeadFromBuffer(data, dataLength))
    {
        PUSH_ERROR("函数 TOrgFile::copyFromBuffer 调用 copyHeadFromBuffer 失败。");
        return false;
    }

    // Data数据复制
    if (dataLength < getHeadLength() + CRCLength + getDataLength())
    {
        PUSH_ERROR("函数 TOrgFile::copyFromBuffer 数据空间不足(datalength=%d, getHeadLength()=%d, CRCLength=%d, getDataLength()=%d。",
                   dataLength, getHeadLength(), CRCLength, getDataLength());
        return false;
    }
    init_crc64_table();
    uint64_t calculatedDataCRC = calculate_crc64(reinterpret_cast<const char *>(data + getHeadLength() + CRCLength), getDataLength());
    if (calculatedDataCRC != storedDataCRC)
    {
        PUSH_ERROR("函数copyFromBuffer Data CRC校验失败。");
        return false;
    }
    if (!copyPtrFromBuffer(data, dataLength))
    {
        PUSH_ERROR("函数 TOrgFile::copyFromBuffer 调用 copyPtrFromBuffer 失败。");
        return false;
    }

    // CRC校验数据
    HeadCRC = calculatedHeadCRC;
    DataCRC = calculatedDataCRC;

    return true;
}
